#!perl  -I /data/scripts/lib

use strict;
use warnings;
#use POSIX qw(strftime);

use IMEI;
use Functions;

#use DBI();
#use File::Basename;
#use File::stat;
use Data::Dumper 'Dumper';

#use IO::Socket;

my $arg="";
my $imei;
my $data;
my %hRefEncipheredData;
my %hRefDecipheredData=();

sub printHashContent
{
    my $hRefParam=shift @_;

    print "Printing Global Hash Content:\n";
    print "######################################################\n";
    foreach my $key (keys %$hRefParam)
    {
	print $key." => ".$hRefParam->{$key}."\n";
    }
    print "######################################################\n";
}

sub validate
{
    my $hRefParam=shift @_;
    my $string=shift @_;
    #my $errcode=0;

    #print "in sub validate: string => ".$string."\n";
    # check the format of the IMEI
    # must be 15 digits
    if(! IMEI::isNumeric($string))
    {
	#exit(101);
	#Functions::error "101 Bad format.\n";
	print $string.";bad_format;;;;;;\n";
	#$errcode=101;
	return 0;
      }
    
    # check the ckecksum of the IMEI
    # use the function isLuhn to validate the number
    #if(! IMEI::check_checksum($imei))
    if(! IMEI::isLuhn($string))
    {
	#exit(102);
	#Functions::error "102 Bad checksum.\n";
	print $string.";bad_checksum;;;;;;\n";
	#$errcode=102;
	return 0;
      }
    
    # check the tac of the IMEI
    # the tac corresponds to the first 6 digits of the IMEI
    # the tac must belong to alcatel
    if(! IMEI::isAlcatelProduct($string,"/data/scripts/tac"))
    {
	#exit(103);
	#Functions::error "103 Not Alcatel / TCT Mobile Phone.\n";
	print $string.";not_alcatel-tct_mobile_phone;;;;;;\n";
	#$errcode++;
	return 0;
      }
    
    return 1;   
}

sub process
{
    my $hRefParam=shift @_;
    my $errcode=0;

    $hRefParam->{DBCONNECT}=Connect::db_con($hRefParam->{DBNAME},$hRefParam->{DBLOGIN},$hRefParam->{DBPASSWD});
    if (! defined $hRefParam->{DBCONNECT})
    {
	Functions::error "Failed to connect to DB.\n";
        # Failed to connect to DB
	return 1;
    }
    #printHashContent($hRefParam);
    
    foreach my $imei (@{$hRefParam->{IMEI_LIST}})
    {
	if(! validate($hRefParam,$imei))
	{
	    #Functions::error "Failed to validate imei\n";
	    next;
	}
	
        # check whether the IMEI exists in DB  
	if(! IMEI::exists($imei,$hRefParam->{DBCONNECT}))
	{
	    #print $imei.";unavailable;;;;;;\n";
	    print $imei.";;;;;;;\n";
	    next;
	}

	# disabled
	# check whether the requester is the owner of the IMEI
	#if(! IMEI::isOwner($imei,$hRefParam->{REQUESTER},$hRefParam->{DBCONNECT}))
	#{
	    #print $imei.";sender_not_allowed;;;;;;\n";
	    #next;
	#} 
	
	# check whether the IMEI is locked
	if(! IMEI::isLocked($imei,"comref",$hRefParam->{DBCONNECT}))
	{
	    print $imei.";not_locked;;;;;;\n";
	    next;
	}
	
	# get enciphered data
	$hRefEncipheredData{$imei} = IMEI::getEncipheredData($hRefParam->{DBCONNECT},$imei);
	#print $hRefEncipheredData{$imei}."\n";
	if($hRefEncipheredData{$imei}=~/KO/)
	{
	    # imei not found in DB
	    print $imei.";;;;;;;\n";

	    # del key/value pair
	    delete $hRefEncipheredData{$imei};
	    next;
	  }
	
	#print $imei." => ".$hRefEncipheredData{$imei}."\n";
	
	#if(defined $data)
	#{
	#$hRefEncipheredData{$imei}=$data;
	if(! IMEI::decipherData(\%hRefEncipheredData,\%hRefDecipheredData))
	{
	    #exit(150);
	    Functions::error "150 Failed to decipher data.\n";
	      #$errcode++;
	      #return $errcode=150;
	      next;
	  }

        # sometimes, DLL only returns 5 keys
        # in this case, a 6th empty field is added to match the format of the result file
	my $count=($hRefDecipheredData{$imei} =~ tr/;//);
	#print ">$count<";
	if($count == 6)
	{
	    #my @fields=split(";",$hRefDecipheredData{$imei});
	    #warn Dumper[@fields];
	    #353205014046971;2958028006;;;;1347714180;
	    #print $fields[0].";".$fields[1].";".$fields[2].";".$fields[3].";".$fields[4].";;".$fields[5]."\n";

	    if($hRefDecipheredData{$imei}=~m/^(([^\;]*\;){5})([^\;]*)\;/)
	    {
		#print "$1\n";		
		#print "$3\n";		
		print "$1;$3;\n";
	    }
	}
	else
	{
	    print $hRefDecipheredData{$imei};
	}
	
    }

    Connect::db_discon($hRefParam->{DBCONNECT});

    return 0;

}

sub parse_args
{
    my $hRefParam=shift @_;

    my $arg="";
    my $err=0;
    
    while ($arg=shift @ARGV)
    {
	chomp($arg);
	if (! exists $hRefParam->{DBNAME})
	{
	    $hRefParam->{DBNAME}=$arg;
	}
	elsif (! exists $hRefParam->{DBLOGIN})
	{
	    $hRefParam->{DBLOGIN}=$arg;
	}
	elsif (! exists $hRefParam->{DBPASSWD})
	{
	    $hRefParam->{DBPASSWD}=$arg;
	}
	elsif (! exists $hRefParam->{REQUESTER})
	{
	    $hRefParam->{REQUESTER}=$arg;
	}
	else
	{
	    if (! exists $hRefParam->{IMEI_LIST})
	    {
		my @list=();
		$hRefParam->{IMEI_LIST}=\@list;
	    }
	    
	    push( @{$hRefParam->{IMEI_LIST}}, $arg);
	}
	
    }	
	
    if (! exists $hRefParam->{IMEI_LIST})
    {
	Functions::error "Missing mandatory arguments..\n";
	  print "Usage: ".$hRefParam->{EXECUTABLE_NAME}." <dbname> <dblogin> <dbpasswd> <requester> [<imei list> ...]\n";
	$err++;
    }
    
    
    if ($err>0)
    {
	return 1;
    }
    
    return 0;
}

sub intro
{
    my $hRefParam=shift @_;
    my $err=0;

    $hRefParam->{EXECUTABLE_NAME}="imei.pl";

    # Following instruction forces flushing for each output to STDOUT
    $|=1;
    
    return $err;
}

sub outro
{
    my $hRefParam=shift @_;
    my $err=0;

    return $err;
}

sub main
{
    my %params=();
    my $errcode;
    
    if (intro(\%params)!=0)
    {
	Functions::error "Error while executing intro. Aborting...\n";
	exit(1);
    }
    
    if (parse_args(\%params)!=0)
    {
	Functions::error "Error while parsing arguments. Aborting...\n";
	  exit(1);
    }

    if(process(\%params)!=0)
    {
	Functions::error "Error while processing. Aborting...\n";
	  exit(1);
    }
}

main();

exit ;

